package ru.aslanov.schedule.server.services;

import com.google.gdata.data.TextConstruct;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import ru.aslanov.schedule.model.DataItem;
import ru.aslanov.schedule.model.DataList;
import ru.aslanov.schedule.model.Entity;
import ru.aslanov.schedule.model.Operation;
import ru.aslanov.schedule.server.AbstractService;
import ru.aslanov.schedule.server.AccessDeniedException;
import ru.aslanov.schedule.server.AccessManager;
import ru.aslanov.schedule.server.gcalendar.GCalendarConnectService;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * Created: Mar 4, 2010 4:40:10 PM
 *
 * @author Sergey Aslanov
 */
public class UserGCalendarService extends AbstractService {

    @Override
    protected Class getEntityClass() {
        throw new UnsupportedOperationException();
    }

    @Override
    protected Object doFetch(HttpServletRequest request) throws Exception {
        final String scheduleKey = request.getParameter("schedule");

        AccessManager am = AccessManager.getInstance();
        am.checkScheduleAdmin(scheduleKey);

        GCalendarConnectService gCalendarConnectService = new GCalendarConnectService(scheduleKey);

        final CalendarFeed calendarsFeed = gCalendarConnectService.getUserCalendarsFeed();

        List<DataItem> dataItems = new ArrayList<DataItem>();
        for (CalendarEntry calendarEntry : calendarsFeed.getEntries()) {
            DataItem dataItem = new DataItem();
            final String calIdStr = calendarEntry.getId();
            final String calId = calIdStr.substring(calIdStr.lastIndexOf("/") + 1);
            setAttr(dataItem, "calendarId", calId);

            final TextConstruct title = calendarEntry.getTitle();
            setAttr(dataItem, "name", title != null ? title.getPlainText() : calId);

            dataItems.add(dataItem);
        }

        DataList dataList = new DataList(dataItems);
        return dataList;
    }

    @Override
    protected String getDefaultInputLang(HttpServletRequest request) {
        return null;
    }

    @Override
    protected boolean checkPermission(Entity existingEntity, HttpServletRequest request, PersistenceManager pm, Operation operation) throws AccessDeniedException {
        return operation == Operation.VIEW;
    }

    @Override
    protected void makeObjectPersistent(PersistenceManager pm, Entity object, HttpServletRequest request) {
        throw new UnsupportedOperationException();
    }
}
